import pandas as pd
import numpy as np
from config import config_database
from app.model.model import Theme


class ServiceTheme(object):
    def __init__(self):
        pass

    # 主题列表
    def list_theme(self):
        res = list()
        data = None
        try:
            data = np.array(pd.read_csv(
                config_database["file_theme"])).tolist()
            for item in data:
                res.append(Theme(item[0], item[1], item[2]).toJson())
            return {"errcode": 200, "errmsg": "ok{filename}", "data": res}
        except:
            return {"errcode": 400, "errmsg": "读取{filename}文件失败".format(filename=config_database['file_theme'])}

    # 主题更新
    def update_theme(self, id, **args):

        data = np.array(pd.read_csv(config_database["file_theme"])).tolist()
        themeList = list()
        for item in data:
            themeList.append(Theme(item[0], item[1], item[2]))

        judge = False

        for item in themeList:
            if item.id == id:
                if 'backgroundColor' in args.keys():
                    item.backgroundColor = args['backgroundColor']
                if 'textColor' in args.keys():
                    item.textColor = args['textColor']
                inList = list()
                for item in themeList:
                    inList.append(item.toList())
                try:
                    pd.DataFrame(inList).to_csv(
                        config_database["file_theme"], index=False, header=['id', 'backgroundColor', 'textColor'])
                    judge = True
                except:
                    return {"errcode": 400, "errmsg": "写入文件{filename}失败".format(filename=config_database['file_theme'])}
                break
            else:
                pass

        if judge is True:
            return {"errcode": 200, "errmsg": "ok"}
        else:
            return {"errcode": 400, "errmsg": "没有该id的主题"}
